/**
 * @description: lazyMan
 * @author: huen2015
 */

import { IFn } from './types'

class LazyMan {
	private queue: IFn[]
	constructor() {
		this.queue = []
		setTimeout(() => {
			this.next()
		})
	}

	next() {
		if (this.queue.length) {
			const fn = this.queue.shift() as IFn
			fn()
		}
	}

	syncFn(callback: IFn = () => {}) {
		const queueFn = () => {
			callback()
			this.next()
		}
		this.queue.push(queueFn)
		return this
	}

	asyncFn(callback: IFn = () => {}, delay: number = 1000) {
		const queueFn = () => {
			setTimeout(() => {
				console.log(`delay ${delay}ms 后`)
				callback()
				this.next()
			}, delay)
		}
		this.queue.push(queueFn)
		return this
	}
}

const lazyMan = new LazyMan()
const say = () => {
	console.log('say')
}
const eat = () => {
	console.log('eat')
}

lazyMan
	.syncFn(() => {
		console.log('lazyMan - begin')
	})
	.asyncFn(say, 4000)
	.asyncFn(eat, 2000)
	.syncFn(() => {
		console.log('lazyMan - end')
	})
